package com.pktechan.api.activeMq;

import com.pktechan.api.vo.TradeOrderExpireDelayed;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.config.SimpleJmsListenerContainerFactory;
import org.springframework.jms.core.JmsMessagingTemplate;

import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Topic;
import java.util.concurrent.DelayQueue;

/**
 * @program: cloudfloating
 * @description: activemq配置类
 * @author: qx.zhang
 * @create: 2021-03-12 15:29
 **/
@Configuration
public class ActiveMQConfig {

    @Value("${activemq.broker-url}")
    private String brokerUrl;

    @Value("${activemq.user-name}")
    private String userName;

    @Value("${activemq.password}")
    private String password;

    @Value("${activemq.cloud-floating-send-mini-message-queue-name}")
    private String sendMiniMessageQueueName;

    @Value("${activemq.cloud-floating-send-mini-message-topic-name}")
    private String sendMiniMessageTopicName;

    @Bean(name = "sendMiniMessageQueueName")
    public Queue sendMiniMessageQueueName() {
        return new ActiveMQQueue(sendMiniMessageQueueName);
    }

    @Bean(name = "sendMiniMessageTopicName")
    public Topic sendMiniMessageTopicName() {
        return new ActiveMQTopic(sendMiniMessageTopicName);
    }

    @Bean
    public ConnectionFactory connectionFactory(){
        return new ActiveMQConnectionFactory(userName, password, brokerUrl);
    }

    @Bean
    public JmsMessagingTemplate jmsMessageTemplate(){
        return new JmsMessagingTemplate(connectionFactory());
    }

    // 在Queue模式中，对消息的监听需要对containerFactory进行配置
    @Bean("queueListener")
    public JmsListenerContainerFactory<?> queueJmsListenerContainerFactory(ConnectionFactory connectionFactory){
        SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setPubSubDomain(false);
        return factory;
    }

    //在Topic模式中，对消息的监听需要对containerFactory进行配置
    @Bean("topicListener")
    public JmsListenerContainerFactory<?> topicJmsListenerContainerFactory(ConnectionFactory connectionFactory){
        SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setPubSubDomain(true);
        return factory;
    }

    @Bean("tradeOrderExpireDelayedQueue")
    public DelayQueue tradeOrderExpireDelayedFactory() {
        return new DelayQueue<TradeOrderExpireDelayed>();
    }
}
